﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;

namespace Asko.Lib.Convertes
{
 public class EdgeRouteToPathConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Point sourcePos, targetPos;
            Size sourceSize, targetSize;
            Point p1, p2;
            PathSegment[] segments;

            #region Get the inputs
            //get the position of the source
            sourcePos = new Point()
            {
                X = (values[0] != DependencyProperty.UnsetValue ? (double)values[0] : 0.0),
                Y = (values[1] != DependencyProperty.UnsetValue ? (double)values[1] : 0.0)
            };
            //get the size of the source
            sourceSize = new Size()
            {
                Width = (values[2] != DependencyProperty.UnsetValue ? (double)values[2] : 0.0),
                Height = (values[3] != DependencyProperty.UnsetValue ? (double)values[3] : 0.0)
            };
            //get the position of the target
            targetPos = new Point()
            {
                X = (values[4] != DependencyProperty.UnsetValue ? (double)values[4] : 0.0),
                Y = (values[5] != DependencyProperty.UnsetValue ? (double)values[5] : 0.0)
            };  
            //get the size of the target
            targetSize = new Size()
            {
                Width = (values[6] != DependencyProperty.UnsetValue ? (double)values[6] : 0.0),
                Height = (values[7] != DependencyProperty.UnsetValue ? (double)values[7] : 0.0)
            };
            #endregion
            //
            // Create the path
            //
            p1 = GraphConverterHelper.CalculateAttachPoint(sourcePos, sourceSize, targetPos);
            p2 = GraphConverterHelper.CalculateAttachPoint(targetPos, targetSize, sourcePos);

            segments = new PathSegment[1];

            Vector v = p1 - p2;
            v = v / v.Length * 10;
            Vector n = new Vector(-v.Y, v.X) * 0.3;

            segments[segments.Length - 1] = new LineSegment(p2, true);


            PathFigureCollection pfc = new PathFigureCollection(2);
            pfc.Add(new PathFigure(p1, segments, false));
            pfc.Add(new PathFigure(p2,
                                     new PathSegment[] {
                                                        new LineSegment(p2 + v - n, true),
                                                        new LineSegment(p2 + v + n, true)}, true));

            return pfc;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

    }
}
